import {
  CheckCircleFilled,
  CopyFilled,
  CopyOutlined,
  MoonOutlined,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import {
  Button,
  Divider,
  Flex,
  FloatButton,
  Grid,
  Progress,
  message,
} from 'antd';
import { toPng } from 'html-to-image';
import moment from 'moment';
import { useMemo, useRef } from 'react';
import './index.less';
// 设置 Moment.js 使用中文语言环境
moment.locale('zh-cn');

// 将周开始日期设置为周一
moment.updateLocale('zh-cn', {
  week: {
    dow: 1, // 周一
  },
});

const { useBreakpoint } = Grid;

const twoColors = {
  '0%': '#94A9D3',
  '100%': '#4566AD',
};

const configs = {
    1: '日报',
    2: '周报',
    3: '月报',
    4: '季报',
    5: '年报',
  },
  week = {
    0: '星期天',
    1: '星期一',
    2: '星期二',
    3: '星期三',
    4: '星期四',
    5: '星期五',
    6: '星期六',
  };

const c = {
  false: {
    color: '#000',
    color1: '#666',
    color2: 'rgba(255,255,255,0.5)',
    bg: 'rgba(255,255,255,0.7)',
    bg1: 'rgba(0,0,0,0.1)',
  },
  true: {
    color: '#fff',
    color1: '#ccc',
    color2: 'rgba(255,255,255,0.2)',
    bg: 'rgba(0,0,0,0.8)',
    bg1: 'rgba(255,255,255,0.1)',
  },
};

function MainTain({ setDrawer }) {
  const { lg } = useBreakpoint();

  const {
    initialState: { curData, type, userName, bgindex, dark },
    setInitialState,
  } = useModel('@@initialState');

  const time = useMemo(() => {
    const obj = {
      1: moment().format('YYYY-MM-DD'),
      2:
        moment().startOf('week').format('YYYY-MM-DD') +
        ' ~ ' +
        moment().endOf('week').format('YYYY-MM-DD'),
      3:
        moment().startOf('month').format('YYYY-MM-DD') +
        ' ~ ' +
        moment().endOf('month').format('YYYY-MM-DD'),
      4:
        moment().startOf('month').format('YYYY-MM-DD') +
        ' ~ ' +
        moment().endOf('month').format('YYYY-MM-DD'),
      5:
        moment().startOf('year').format('YYYY-MM-DD') +
        ' ~ ' +
        moment().endOf('year').format('YYYY-MM-DD'),
    };
    return obj[type];
  }, [type]);

  const progressfz = curData?.reduce((prev, cur) => {
    return (
      prev +
      cur.list.reduce((p, c) => {
        return p + c.progress;
      }, 0)
    );
  }, 0);

  const allmission = curData?.reduce((prev, cur) => {
    return prev + cur.list.length;
  }, 0);

  const domRef = useRef();

  const handleCopyImage = async () => {
    try {
      const dataUrl = await toPng(domRef.current, { pixelRatio: 2 });
      const blob = await fetch(dataUrl).then((res) => res.blob());
      const clipboardItem = new ClipboardItem({ 'image/png': blob });
      await navigator.clipboard.write([clipboardItem]);
      message.success('图片已复制到剪贴板');
    } catch (error) {
      message.error('复制图片失败：', error);
    }
  };
  console.log('====================================');
  console.log(bgindex);
  console.log('====================================');

  return (
    <Flex
      vertical={true}
      justify="center"
      align="center"
      style={{
        flex: 1,
        backgroundColor: '#f9f9f9',
        flexShrink: 0,
        maxWidth: '100%',
        height: '100%',
        overflow: 'hidden',
        gap: 12,
      }}
    >
      <FloatButton.Group
        shape="circle"
        style={{
          right: 24,
          bottom: 24,
          zIndex: 9999,
        }}
      >
        <FloatButton
          icon={<MoonOutlined />}
          size='large'
          type={dark ? 'primary' : 'default'}
          onClick={() => {
            setInitialState((s) => {
              return {
                ...s,
                dark: !dark,
              };
            });
          }}
        />
        <FloatButton
          icon={<CopyFilled />}
          type="primary"
          onClick={handleCopyImage}
        />
      </FloatButton.Group>

      <div
        className="element"
        style={{
          position: 'relative',
          borderRadius: 16,
          flexShrink: 0,
          backgroundColor: '#f9f9f9',
          color: c[dark].color,
        }}
      >
        <div
          style={{
            zIndex: 999,
            borderRadius: 16,
            position: 'inherit',
            overflow: 'hidden',
            backgroundImage:
              bgindex === 'video'
                ? 'none'
                : bgindex?.includes?.('base')
                ? `url("${bgindex}")`
                : `url(${require(`@/assets/p${bgindex}.jpg`)})`,
            position: 'relative',
          }}
          className="bg"
          ref={domRef}
        >
          {bgindex === 'video' && (
            <video
              src="./demo.mp4"
              autoPlay
              controls={false}
              muted
              loop
              className="fit"
              style={{
                position: 'absolute',
                zIndex: 0,
                width: '110%',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                margin: 'auto',
              }}
            ></video>
          )}
          <div className="containers">
            <div className="spread" style={{ color: c[dark].color1 }}>
              <b className="time">{time}</b>

              <span className="time" style={{ fontSize: 14 }}>
                {moment().format('MM-DD')} {week[moment().day()]}
              </span>
            </div>

            <Divider style={{ backgroundColor: c[dark].color2 }}></Divider>
            <div className="spread" style={{ alignItems: 'center' }}>
              <h2 style={{ margin: 0 }}>
                {userName} 的{configs[type]}
              </h2>
              <div
                style={{ flexDirection: 'column' }}
                className="flex justify-end align-end"
              >
                <div className="flex gap-10" style={{ alignItems: 'baseline' }}>
                  <span style={{ fontSize: 14, opacity: 0.6 }}>项/任务</span>
                  <b style={{ fontSize: 18, color: '#333' }}>
                    <span className="iconbg">{curData.length}</span>/
                    <span className="iconbg">{allmission}</span>
                  </b>
                </div>
                <Progress
                  style={{ width: 145, margin: '10px 16px 0 0' }}
                  size={'small'}
                  percent={progressfz / allmission}
                  trailColor={c[dark].bg1}
                  format={(val) =>
                    val === 100 ? (
                      <CheckCircleFilled style={{ color: '#4566AD' }} />
                    ) : (
                      <span style={{ color: c[dark].color1 }}>
                        {parseInt(val) + '%'}
                      </span>
                    )
                  }
                  strokeColor={twoColors}
                ></Progress>
              </div>
            </div>
          </div>
          <div className="carda">
            <ul className="curDatas">
              {curData.map(({ project, list, ...other }, index) => {
                const progresses = list.reduce((prev, cur) => {
                  return prev + cur.progress;
                }, 0);
                const allprogress = list.length * 100;

                return (
                  <li key={other.id} style={{ backgroundColor: c[dark].bg }}>
                    <div className="spread">
                      <div>{project}</div>
                      <Progress
                        style={{ width: 145 }}
                        trailColor={c[dark].bg1}
                        size={'small'}
                        percent={
                          parseFloat(progresses / allprogress).toFixed(3) * 100
                        }
                        format={(val) =>
                          val === 100 ? (
                            <CheckCircleFilled style={{ color: '#829ACA' }} />
                          ) : (
                            <span style={{ color: c[dark].color1 }}>
                              {parseInt(val) + '%'}
                            </span>
                          )
                        }
                        strokeColor={'#829ACA'}
                      ></Progress>
                    </div>

                    <div>
                      {list?.map(({ id, name, progress }, index) => {
                        return (
                          <div
                            key={id}
                            className="flex gap-10 justify-start align-center"
                            style={{ marginBottom: 24 }}
                          >
                            <div
                              className="iconbgs"
                              style={{
                                backgroundColor: c[dark].bg1,
                                color: c[dark].color,
                              }}
                            >
                              {index + 1}
                            </div>
                            <Progress
                              type="circle"
                              percent={progress}
                              size={20}
                              status="active"
                              strokeColor={'#829ACA'}
                              trailColor={c[dark].bg1}
                            ></Progress>
                            <div className="flex-1">{name}</div>
                          </div>
                        );
                      })}
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
      {!lg && (
        <Flex>
          <Button
            style={{ alignSelf: 'flex-end' }}
            type="primary"
            onClick={() => {
              setDrawer((s) => ({
                ...s,
                open: true,
              }));
            }}
          >
            编辑
          </Button>
        </Flex>
      )}
    </Flex>
  );
}

export default MainTain;
